package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.MqConstant;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.es.SkuHasStockVo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WmsWareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WmsWareOrderTaskEntity;
import com.atguigu.gulimall.ware.feign.OrderFeign;
import com.atguigu.gulimall.ware.feign.WareFeign;
import com.atguigu.gulimall.ware.service.WmsWareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WmsWareOrderTaskService;
import com.atguigu.gulimall.ware.vo.CartItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WmsWareSkuDao;
import com.atguigu.gulimall.ware.entity.WmsWareSkuEntity;
import com.atguigu.gulimall.ware.service.WmsWareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;


@Service("wmsWareSkuService")
public class WmsWareSkuServiceImpl extends ServiceImpl<WmsWareSkuDao, WmsWareSkuEntity> implements WmsWareSkuService {
    @Resource
    private WareFeign wareFeign;
    @Resource
    private WmsWareSkuDao wareSkuDao;
    @Resource
    private WmsWareOrderTaskService wmsWareOrderTaskService;
    @Resource
    private WmsWareOrderTaskDetailService wmsWareOrderTaskDetailService;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private OrderFeign orderFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * skuId
         * wareId
         */
        QueryWrapper<WmsWareSkuEntity> queryWrapper=new QueryWrapper<>();
        String wareId= (String) params.get("wareId");
        String skuId= (String) params.get("skuId");
        if(StringUtils.isNotBlank(wareId)) queryWrapper.eq("ware_id",wareId);
        if(StringUtils.isNotBlank(skuId) && !"".equals(skuId)) queryWrapper.eq("sku_id",skuId);
        IPage<WmsWareSkuEntity> page = this.page(
                new Query<WmsWareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    //采购需求入库
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        QueryWrapper<WmsWareSkuEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("sku_id",skuId);
        queryWrapper.eq("ware_id",wareId);
        List<WmsWareSkuEntity> list = this.list(queryWrapper);
        //如果没有库存信息则新增
        WmsWareSkuEntity wmsWareSkuEntity=new WmsWareSkuEntity();
        if(CollectionUtils.isEmpty(list)){
            wmsWareSkuEntity.setSkuId(skuId);
            wmsWareSkuEntity.setWareId(wareId);
            wmsWareSkuEntity.setStock(skuNum);
            try {
                R info = wareFeign.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("pmsSkuInfo");
                if(info.getCode() == 0){
                    wmsWareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            }catch (Exception e){
                System.out.println("com.firenay.mall.ware.service.impl.WareSkuServiceImpl：远程调用出错");
            }
            this.save(wmsWareSkuEntity);
        }else{
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            Integer skuHasStock = wareSkuDao.getSkuHasStock(skuId);
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            skuHasStockVo.setSkuId(skuId);
            if(skuHasStock==null){
                skuHasStockVo.setHasStock(false);
            } else if (skuHasStock > 0) {
                skuHasStockVo.setHasStock(true);
            } else {
                skuHasStockVo.setHasStock(false);
            }

            return skuHasStockVo;
        }).collect(Collectors.toList());
        return collect;
    }

    @Transactional
    @Override
    public Boolean lockStock(WareSkuLockVo wareSkuLockVo) {
        List<CartItemVo> cartItemVos=wareSkuLockVo.getCartItemVoList();
        //保存任务单
        WmsWareOrderTaskEntity wmsWareOrderTaskEntity=new WmsWareOrderTaskEntity();
        wmsWareOrderTaskEntity.setOrderSn(wareSkuLockVo.getOrderSn());
        wmsWareOrderTaskService.save(wmsWareOrderTaskEntity);
        if(cartItemVos!=null && cartItemVos.size()>0){
            List<SkuWareHasStock> skuWareHasStockList  = cartItemVos.stream().map(item -> {
                SkuWareHasStock wareHasStock = new SkuWareHasStock();
                wareHasStock.setSkuId(item.getSkuId());
                wareHasStock.setWareId(wareSkuDao.listWareIdHasSkuStock(item.getSkuId()));
                wareHasStock.setNum(item.getCount());
                return wareHasStock;
            }).collect(Collectors.toList());
            for (SkuWareHasStock skuWareHasStock:skuWareHasStockList) {
                Boolean skuStocked = false;
                List<Long> wareIds = skuWareHasStock.getWareId();
                if(wareIds!=null && wareIds.size()>0){
                    for (Long wareId:wareIds) {
                        Long count = wareSkuDao.lockSkuStock(skuWareHasStock.getSkuId(), wareId, skuWareHasStock.getNum());
                        if(count>0){
                            //保存任务详情单
                            WmsWareOrderTaskDetailEntity wmsWareOrderTaskDetailEntity=new WmsWareOrderTaskDetailEntity();
                            wmsWareOrderTaskDetailEntity.setTaskId(wmsWareOrderTaskEntity.getId());
                            wmsWareOrderTaskDetailEntity.setWareId(wareId);
                            wmsWareOrderTaskDetailEntity.setSkuId(skuWareHasStock.getSkuId());
                            wmsWareOrderTaskDetailEntity.setSkuNum(skuWareHasStock.getNum());
                            wmsWareOrderTaskDetailEntity.setLockStatus(1);
                            wmsWareOrderTaskDetailService.save(wmsWareOrderTaskDetailEntity);
                            StockLockedTo stockLockedTo=new StockLockedTo();
                            StockDetailTo stockDetailTo=new StockDetailTo();
                            stockLockedTo.setId(wmsWareOrderTaskEntity.getId());
                            BeanUtils.copyProperties(wmsWareOrderTaskDetailEntity,stockDetailTo);
                            stockLockedTo.setStockDetailTo(stockDetailTo);
                            //发送锁定消息给延时队列
                            rabbitTemplate.convertAndSend(MqConstant.WARE_EVENT_EXCHANGE,MqConstant.WARE_DELAY_ROUTING_KEY,stockLockedTo);
                            //库存锁定成功
                            skuStocked=true;
                            break;
                        }
                    }
                    if(!skuStocked){
                        throw new NoStockException(skuWareHasStock.getSkuId()+"商品库存不足");
                    }
                }else{
                    throw new NoStockException(skuWareHasStock.getSkuId()+"商品库存不足");
                }
            }
        }
        return true;
    }

    //解锁库存
    public void unLock(StockLockedTo stockLockedTo){
        /**
         * 库存解锁分为以下场景
         * 1:   未查询到库存任务单    无需解锁
         * 2:   查询到库存任务单
         *    2-1： 未查询到订单    需要解锁
         *    2-2：  查询到库存单,库存单状态为取消：   解锁
         *    2-3：  查询到库存单,库存单状态不为取消：   无需解锁
         */

        WmsWareOrderTaskEntity  orderTaskEntity = wmsWareOrderTaskService.getById(stockLockedTo.getId());
        if(orderTaskEntity==null){
            //场景1
        }else{
            StockDetailTo stockDetailTo = stockLockedTo.getStockDetailTo();
            OrderVo orderBySn = orderFeign.getOrderBySn(orderTaskEntity.getOrderSn());
            if(orderBySn==null){
                //场景2-1
                this.stockUnLock(stockDetailTo);
            }else{
                if(orderBySn.getStatus()==4){
                    //场景2-2
                    this.stockUnLock(stockDetailTo);
                }else{
                    //场景2-3
                }
            }
        }
    }

    //解锁库存,还原库存数量
    @Transactional
    public void stockUnLock(StockDetailTo stockDetailTo){
        //将任务太状态改为已解锁
        WmsWareOrderTaskDetailEntity detailEntity=new WmsWareOrderTaskDetailEntity();
        detailEntity.setId(stockDetailTo.getId());
        detailEntity.setLockStatus(2);
        wmsWareOrderTaskDetailService.updateById(detailEntity);
        //还原库存数量
        wareSkuDao.returnStock(stockDetailTo);

    }

    @Data
    public class SkuWareHasStock{
        private Long skuId;

        private List<Long> wareId;

        private Integer num;

    }

}